module Hexena.Cmds.ReadMZ (run) where
  
import Data.Binary.Get
import Data.Binary.Put
import Data.IFF
import Data.Maybe
import System.Environment (getArgs)
import Text.Printf (printf)
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as L

import Hexena.MZHeader
import Hexena.PEHeader


{-main :: IO ()
main = do 
  arg <- getArgs 
  mapM_ main1 arg

main1 :: String -> IO ()
main1 arg = do
  dat <- L.readFile arg
  -- putStrLn arg
  -- print $ L.length dat
  let (mzhdr, lfanew) = runGet checkFile dat
  -- print mzhdr
  putStrLn $ printf "%s: lfanew = $%08x, mzDistance = %e" arg lfanew (mzDistance $ L.unpack dat)
  -- print $ L.take 512 $ L.drop (fromIntegral lfanew) dat
  let pehdr = readPEFrom dat
  print pehdr
  print $ peOptionalHeader pehdr
  -- let chunks =
  --      [ Cons (chunkIdFromString "FNAM") $ Chunk $ B8.pack arg
  --      , Cons (chunkIdFromString "MZHD") $ Chunk $ B8.concat $ L.toChunks $ L.take 64 dat
  --      , Cons (chunkIdFromString "LFAN") $ Chunk $ B8.concat $ L.toChunks $ runPut $ putWord32be lfanew
  --      ]
  -- B8.writeFile (arg ++ ".exhdr") $ toB8yteString $ Cons (chunkIdFromString "EXHD") (Form chunks)
  -- tmp <- B8.readFile (arg ++ ".exhdr")
  -- let iff = fromJust $ fromB8yteString tmp
  -- print iff
  -- -- print $ parts $ fromJust iff
  -- print $ content $ chunk $ head $ Prelude.filter ((== chunkIdFromString "LFAN") . chunkId) $ parts $ chunk iff-}

runner :: FilePath -> IO ()
runner fn = do
  dat <- L.readFile fn
  let (mzhdr, lfanew) = runGet checkFile dat
  putStrLn $ printf "%s: lfanew = $%08x, mzDistance = %e" fn lfanew (mzDistance $ L.unpack dat)
  let pehdr = readPEFrom dat
  print pehdr
  print $ peOptionalHeader pehdr

run :: [FilePath] -> IO ()
run fns = mapM_ runner fns
